const sequelize = require('../db.js')
const { QueryTypes } = require('sequelize');
const jwt = require('jsonwebtoken')
const router = require('koa-router')()
const user = require('../model/user.js')
router.prefix('/users')

router.get('/', async function (ctx, next) {
  ctx.body = await user.findAll()
})

router.post('/add', async function (ctx, next) {
  try{
    const {name,password} = ctx.request.body
    const res = user.create({name,password})
    ctx.body = {
      msg:'操作成功',
      code:200,
      data:res
    }
  }catch{
    ctx.body = '异常'
  }
  
})
router.post('/login',async ctx=>{
  const {name,password} = ctx.request.body
  const pswd = await sequelize.query(`select * from user where name = '${name}' and password='${password}'`,{ type: QueryTypes.SELECT })
if(pswd.length){
  ctx.body = {
    code:200,
    msg:'登陆成功',
    data:jwt.sign({name:name,id:pswd[0].id},'yan',{ expiresIn: '7h' })
  }
}else{
  ctx.body = {
    code:401,
    msg:'用户名或密码错误'
  }
}
} )
module.exports = router
